package main

import (
	"fmt"
	"gitee.com/benben-mao/djson"
	"gitee.com/benben-mao/mc"
	"gitee.com/benben-mao/mc/example/controller"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"net/http"
	"time"
	"unicode/utf8"
)


func main() {

	gin.SetMode("debug")

	r := gin.Default()

	r.StaticFS("/static", http.Dir("./static"))
	// 加载模版
	r.SetFuncMap(mc.TemplateFuncMap)
	r.LoadHTMLGlob("./templates/**/*.html")

	r.NoMethod(mc.HandlerAdapt)
	r.NoRoute(mc.HandlerAdapt)


	option := mc.Default() // 一定要在加载模版之后，否则默认widget不会加载
	option.Response.ErrorTemplate = "base/error.html"
	option.Response.MessageTemplate = "base/message.html"
	option.Request.PageSizeName = "limit"
	option.Request.PageName = "page"
	option.Response.AjaxRenderType = mc.RenderTypeAsciiJSON
	option.Router.ControllerMap = controller.ControllerMap

	option.Response.FootName = "totalRow"
	option.Response.TotalName = "count"
	option.Response.SuccessCodeValue = "0"
	option.Logs = []mc.LogOption{
		{"default", "./logs/mc.log"},
	}

	option.GetModelConfigCallback = func(modelName string) (content interface{}, scripts []djson.Script) {
		content = fmt.Sprintf("./mconfigs/%s.json", modelName)
		return
	}

	mc.Init(r)

	initDbConn()

	mc.SetValidations([]mc.Validation{
		{Tag:"username", Func:checkUserName, ErrMsg:"{0} 长度不能小于6位·11111"},
	})


	r.Use(mc.MiddlewareLogToFile, mc.MiddlewareRecover)

	r.GET("/", func(c *gin.Context) { c.Redirect(302, "/home/index/index") })



	err := r.Run(fmt.Sprintf("%s:%d", "0.0.0.0", 8111))
	if err != nil {
		panic(mc.ErrorInternalServerError.Copy(err.Error()))
	}
}

func checkUserName (f validator.FieldLevel) bool {
	count := utf8.RuneCountInString(f.Field().String())
	return count >= 6
}




func initDbConn() {

	newLogger := logger.New(
		log.New(mc.SqlLogOut, "\r\n", log.LstdFlags), //  io writer
		logger.Config{
			SlowThreshold: 0,           //  慢 SQL 阈值
			LogLevel:      logger.Info, //  Log level
			Colorful:      true,        //  禁用彩色打印
		},
	)

	dsn := "root:123456@tcp(127.0.0.1:3306)/mc_test?charset=utf8mb4&parseTime=true&loc=Local"
	db, err := gorm.Open(
		mysql.New(mysql.Config{DSN:dsn, DisableDatetimePrecision:true}),
		&gorm.Config{Logger:newLogger},
	)
	if err != nil {
		panic(mc.ErrorInternalServerError.Copy("数据库连接错误"))
	}

	if sqlDB, err := db.DB(); err == nil && sqlDB != nil {
		sqlDB.SetMaxIdleConns(10)
		sqlDB.SetMaxOpenConns(10)
		sqlDB.SetConnMaxLifetime(time.Minute * time.Duration(20))
		sqlDB.SetConnMaxIdleTime(time.Minute * time.Duration(20))
	}else {
		panic(mc.ErrorInternalServerError.Copy("数据库连接失败"))
	}

	_ = mc.AppendDB("default", db)
}



